﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;

namespace JRBase
{
    public class AnimatedSprite : Sprite
    {
        private float scale;
        private int elapsedTime;
        private int frameTime;
        private int frameCount;
        private int currentFrame;
        private Color color;
        private Rectangle sourceRect = new Rectangle();
        private Rectangle destinationRect = new Rectangle();
        private bool looping;

        public bool Looping
        {
            get { return looping; }
        }
        
        public void Initialize(Texture2D texture, Vector2 position,
                        int frameWidth, int frameHeight, int frameCount,
                        int frametime, Color color, float scale, bool looping)
        {
            base.active = true;
            base.texture = texture;
            base.position = position;
            base.width = frameWidth;
            base.height = frameHeight;

            this.color = color;
            this.frameCount = frameCount;
            this.frameTime = frametime;
            this.scale = scale;
            this.looping = looping;
            
            elapsedTime = 0;
            currentFrame = 0;
        }

        public override void Update(GameTime gameTime)
        {
            if (base.active == false)
                return;

            elapsedTime += (int)gameTime.ElapsedGameTime.TotalMilliseconds;
            if (elapsedTime > frameTime)
            {
                currentFrame++;
                if (currentFrame == frameCount)
                {
                    currentFrame = 0;
                    if (Looping == false)
                        Active = false;
                }
                elapsedTime = 0;
            }
            sourceRect = new Rectangle(currentFrame * base.width, 0, base.width, base.height);
           
            destinationRect = new Rectangle((int)position.X - (int)(base.width * scale) / 2,
                                            (int)position.Y - (int)(base.height * scale) / 2,
                                            (int)(base.width * scale),
                                            (int)(base.height * scale));
        }

        public override void Draw(SpriteBatch spriteBatch)
        {
            if (base.active)
            {
                try
                {
                    spriteBatch.Draw(base.texture, destinationRect, sourceRect, color);
                }
                catch(Exception ex)
                {
                }
            }
        }
    }
}
